// 修改App.tsx，使用直接定义的路由而不是复杂的动态生成
import React, { useState, useEffect } from 'react';
import { ConfigProvider, App as AntdApp, theme } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import { Routes, Route, Navigate } from 'react-router-dom';
import Login from './views/login/Login';
import MainLayout from './layouts/MainLayout';
import './App.css';
import { STORAGE_KEYS, THEMES } from './constants/common';
import { useSelector } from 'react-redux';
import { RootState } from './store';

function App() {
  // 获取Redux中保存的主题设置
  const currentTheme = useSelector((state: RootState) => state.settings?.theme) || THEMES.LIGHT;
  
  // 使用useState钩子管理认证状态，这样可以在状态变化时触发重新渲染
  const [isAuthenticated, setIsAuthenticated] = useState(() => {
    const hasToken = !!localStorage.getItem('token');
    return hasToken;
  });

  // 初始化主题
  useEffect(() => {
    // 从本地存储获取主题设置
    const savedTheme = localStorage.getItem(STORAGE_KEYS.THEME) || THEMES.LIGHT;
    
    // 设置document根元素的主题属性
    document.documentElement.setAttribute('data-theme', savedTheme);
  }, []);

  // 监听localStorage变化以及路由变化
  useEffect(() => {
    // 检查localStorage中token的状态
    const checkAuth = () => {
      const hasToken = !!localStorage.getItem('token');
      if (isAuthenticated !== hasToken) {
        setIsAuthenticated(hasToken);
      }
    };

    // 初始检查
    checkAuth();
    
    // 添加storage事件监听器
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === 'token') {
        checkAuth();
      }
    };
    
    // 使用更长的间隔减少频繁检查
    const interval = setInterval(checkAuth, 2000);

    window.addEventListener('storage', handleStorageChange);
    
    return () => {
      clearInterval(interval);
      window.removeEventListener('storage', handleStorageChange);
    };
  }, [isAuthenticated]);

  // 监听token全局事件（为了解决同一窗口不触发storage事件的问题）
  useEffect(() => {
    const handleTokenUpdate = () => {
      const hasToken = !!localStorage.getItem('token');
      setIsAuthenticated(hasToken);
    };

    // 添加自定义事件监听
    window.addEventListener('token-updated', handleTokenUpdate);
    
    return () => {
      window.removeEventListener('token-updated', handleTokenUpdate);
    };
  }, []);

  return (
    <ConfigProvider 
      locale={zhCN} 
      theme={{ 
        token: { colorPrimary: '#1890ff' },
        algorithm: currentTheme === THEMES.DARK ? theme.darkAlgorithm : theme.defaultAlgorithm
      }}
    >
      <AntdApp>
        <Routes>
          {/* 登录页 */}
          <Route path="/login" element={
            !isAuthenticated ? <Login /> : <Navigate to="/home" replace />
          } />
          
          {/* 主应用布局 - 所有受保护的路由都通过MainLayout展示 */}
          <Route path="/*" element={
            isAuthenticated ? <MainLayout /> : <Navigate to="/login" replace />
          } />
          
          {/* 根路径重定向 */}
          <Route path="/" element={
            <Navigate to={isAuthenticated ? "/home" : "/login"} replace />
          } />
        </Routes>
      </AntdApp>
    </ConfigProvider>
  );
}

export default App;